package game.views;

import haxe.Timer;
import hx.display.UILoadScene;
import motion.Actuate;
import hx.display.Quad;
import hx.display.Scene;

/**
 * 切换效果
 */
class ExchangeEffect extends Scene implements hx.display.ISceneExchangeEffect {
	public function onReadyExchange(scene:Scene, onLoaded:() -> Void) {
		var tileWidth = this.stage.stageWidth / 16;
		var tileHeight = tileWidth;
		var heightCounts = Std.int(this.stage.stageHeight / tileHeight) + 1;
		// 显示方块逻辑
		var array:Array<Quad> = [];
		for (iy in 0...heightCounts) {
			for (ix in 0...16) {
				var quad = new Quad(tileWidth, tileHeight);
				quad.alpha = 0.;
				this.addChild(quad);
				quad.x = ix * tileWidth;
				quad.y = iy * tileHeight;
				Actuate.tween(quad, (1 + ix + iy * 16) * 0.005, {alpha: 1});
				array.push(quad);
			}
		}
		// 隐藏方块逻辑
		function hide():Void {
			this.mouseEnabled = false;
			for (index => quad in array) {
				var t = Actuate.tween(quad, (index + 1) * 0.005, {alpha: 0});
				if (index == array.length - 1) {
					t.onComplete(() -> {
						this.parent?.removeChild(this);
					});
				}
			}
		}
		Actuate.timer(heightCounts * 16 * 0.005).onComplete(() -> {
			// 检查是否已经载入完毕
			function check():Void {
				if (scene is UILoadScene) {
					var uiLoad:UILoadScene = cast scene;
					if (!uiLoad.uiAssets.loading) {
						onLoaded();
						hide();
					} else {
						// 一段时间检测
						Timer.delay(check, 100);
					}
				} else {
					onLoaded();
					hide();
				}
			}
			check();
		});
	}
}
